package com.concurrent.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.Query;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Set;

/**
 * Created by zhangjiawen on 2019/8/13.
 */
@RestController
@RequestMapping("/redis")
public class redisController {
    @Autowired
    private StringRedisTemplate redisTemplate;
    private static final String publicKey="CommonKey";

    public redisController() throws UnknownHostException, MalformedObjectNameException {
    }


    @RequestMapping("/hello")
    public String hello(){
        return "hello World";
    }
@RequestMapping("/setnx")
    public String setNx() throws MalformedObjectNameException {
        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(publicKey, getIp()+":"+getPort());
    return redisTemplate.opsForValue().get(publicKey);
    }

private String getPort() throws MalformedObjectNameException {
    MBeanServer beanServer = ManagementFactory.getPlatformMBeanServer();
    Set<ObjectName> objectNames = beanServer.queryNames(new ObjectName("*:type=Connector,*"),
            Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
    String port = objectNames.iterator().next().getKeyProperty("port");
    return port;
}

    private String getIp(){
        InetAddress addr = null;
        try {
            addr = InetAddress.getLocalHost();
        } catch (Exception e) {
            e.printStackTrace();
        }
        byte[] ipAddr = addr.getAddress();
        String ipAddrStr = "";
        for (int i = 0; i < ipAddr.length; i++) {
            if (i > 0) {
                ipAddrStr += ".";
            }
            ipAddrStr += ipAddr[i] & 0xFF;
        }
        return ipAddrStr;

    }

}
